package com.taotao.manage.service;

import com.taotao.manage.pojo.ContentCategory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ContentCategoryServiceImpl extends BaseServiceImpl<ContentCategory> implements ContentCategoryService {
    /**
     * 新增内容分类
     */
    @Override
    public ContentCategory saveContentCategory(ContentCategory contentCategory) {
        contentCategory.setIsParent(false);
        contentCategory.setStatus(1);
        contentCategory.setSortOrder(1);
        saveSelective(contentCategory);

        ContentCategory parent = new ContentCategory();
        parent.setId(contentCategory.getParentId());
        parent.setIsParent(true);

        updateSelective(parent);

        return contentCategory;

    }
    /**
     * 删除内容分类
     */
    @Override
    public void deleteContentCategory(ContentCategory contentCategory) {
        List<Long> ids=new ArrayList<>();
        ids.add(contentCategory.getId());

        getCategoryIds(ids,contentCategory.getId());
        deleteByIds(ids.toArray(new Long[]{}));

        ContentCategory param = new ContentCategory();
        param.setParentId(contentCategory.getParentId());
        Integer count = queryCountByWhere(param);
        if (count==0){
            ContentCategory parent = new ContentCategory();
            parent.setId(contentCategory.getParentId());
            parent.setIsParent(false);
            updateSelective(parent);
        }
    }

    /**
     * 获取id节点的所有子孙节点
     */
    private void getCategoryIds(List<Long> ids, Long id) {
        ContentCategory category = new ContentCategory();
        category.setParentId(id);
        List<ContentCategory> list = queryListByWhere(category);
        if(list!=null&&list.size()>0){
            for (ContentCategory cc : list) {
                ids.add(cc.getId());
                getCategoryIds(ids,cc.getId());
            }
        }
    }
}
